package com.huanxing.cloud.order.job;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huanxing.cloud.common.core.constant.SecurityConstants;
import com.huanxing.cloud.common.myabtis.tenant.HxTenantContextHolder;
import com.huanxing.cloud.order.api.entity.OrderInfo;
import com.huanxing.cloud.order.api.enums.OrderStatusEnum;
import com.huanxing.cloud.order.service.IOrderInfoService;
import com.huanxing.cloud.upms.api.entity.SysTenant;
import com.huanxing.cloud.upms.api.feign.RemoteTenantService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单相关定时任务
 *
 * @author lijx
 * @date 2022/11/02
 */
@Component
@RequiredArgsConstructor
public class OrderJobHandler {

	private final IOrderInfoService orderInfoService;

	private final RemoteTenantService remoteTenantService;

	/**
	 * 扫描超时未支付订单
	 *
	 * @author lijx
	 * @date 2022/11/02
	 * @return: void
	 */
	@XxlJob("orderCancelJobHandler")
	public void orderCancelJobHandler() throws Exception {
		XxlJobHelper.log("扫描超时未支付订单, orderCancelJobHandler.");
		List<SysTenant> listSysTenant = remoteTenantService.list(SecurityConstants.SOURCE_IN).getData();
		if (!CollectionUtils.isEmpty(listSysTenant)) {
			listSysTenant.forEach(sysTenant -> {
				HxTenantContextHolder.setTenantId(sysTenant.getId());
				// 查询待支付状态并且已超时的订单
				List<OrderInfo> orderList = orderInfoService.list(Wrappers.<OrderInfo>lambdaQuery()
					.eq(OrderInfo::getStatus, OrderStatusEnum.STATUS_1.getCode())
					.lt(OrderInfo::getCreateTime, LocalDateTime.now().minusMinutes(30)));
				orderList.forEach(orderInfoService::cancelOrder);
				HxTenantContextHolder.removeTenantId();
			});
		}
		// default success
	}

}
